uniform vec4 texlimits;
uniform vec2 wsize;

void main() {
    
    vec3 normal, lightDir;
    vec4 diffuse, ambient, globalAmbient;
    float NdotL;
    vec4 color, specular = vec4(0.0, 0.0, 0.0, 0.0);
    
    normal = normalize(gl_NormalMatrix * gl_Normal);
    lightDir = normalize(vec3(gl_LightSource[0].position));
    NdotL = max(dot(normal, lightDir), 0.0);
    diffuse = gl_FrontMaterial.diffuse * gl_LightSource[0].diffuse;
    
    ambient = gl_FrontMaterial.ambient * gl_LightSource[0].ambient;
    globalAmbient = gl_LightModel.ambient * gl_FrontMaterial.ambient;
    
    diffuse = gl_FrontMaterial.diffuse * gl_LightSource[0].diffuse;
    
    if (NdotL > 0.0) {    
        float NdotHV = max(dot(normal, gl_LightSource[0].halfVector.xyz),0.0);
        specular = gl_FrontMaterial.specular * gl_LightSource[0].specular * pow(NdotHV,gl_FrontMaterial.shininess);
    }    
    
    color =  NdotL * diffuse + globalAmbient + ambient + specular;
    
    vec2 pmin = 2.0 * (vec2(texlimits.x, texlimits.y) / wsize.x) - 1.0;
    vec2 pmax = 2.0 * (vec2(texlimits.z, texlimits.w) / wsize.y) - 1.0;
    vec4 p = ftransform();
    
    if (p.x > pmin.x && p.x < pmax.x && p.y > pmin.y && p.y < pmax.y) {
    //if (gl_Vertex.x > -1.0 && gl_Vertex.x < 1.0) {
        gl_FrontColor = color;
        //gl_TexCoord[0] = vec4(rel, 0.0, 1.0);
        gl_FrontColor = vec4(0.0, 1.0, 0.0, 1.0);      
    } else {
        gl_FrontColor = color;
    }
        
    gl_Position = ftransform();
}
